<template>
    <div class="insert-contis">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/warehouse/diaobomingxi' }">盘点明细仓库列表</el-breadcrumb-item>
            <el-breadcrumb-item>新增盘点明细表仓库</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-form ref="formRef" :model="form" label-width="120px" :rules="formRules">
                <el-form-item label="明细ID" prop="id">
                    <el-input v-model="form.id" disabled placeholder="后端自动生成"></el-input>
                </el-form-item>
                <el-form-item label="盘点ID" prop="dian">
                    <el-input v-model="form.didan" disabled placeholder="关联盘点ID"></el-input>
                </el-form-item>
                <el-form-item label="选择物料ID" prop="wuliao" :rules="[{ required: true, message: '选择物料ID' }]">
                    <el-select v-model="form.wuliao" placeholder="请选择该物料" clearable filterable
                        @change="handleMaterialChange">
                        <el-option v-for="material in materialList" :key="material.materialId"
                            :value="material.materialId" :label="`${material.materialId}`"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="输入批次号" prop="pici" :rules="[{ required: true, message: '请输入批次号' }]">
                    <el-input v-model="form.pici"></el-input>
                </el-form-item>
                <el-form-item label="系统账面数量" prop="typediaoru" :rules="[{ required: true, message: '请输入系统账面数量' }]">
                    <el-input v-model="form.typediaoru" type="number" step="0.01" @input='calcDifference'></el-input>
                </el-form-item>
                <el-form-item label="盘点实际数量" prop="diaoboleix" :rules="[{ required: true, message: '输入盘点实际数量' }]">
                    <el-input v-model="form.diaoboleix" type="number" @input='calcDifference'></el-input>
                </el-form-item>
                <el-form-item label="差异数量" prop="chayi">
                    <el-input v-model="form.chayi" type="number" disabled placeholder="自动计算"></el-input>
                </el-form-item>
                <el-form-item label="差异原因" prop="chaiyiyuanyin">
                    <el-select v-model="form.chaiyiyuanyin" placeholder="选择差异原因">
                        <el-option v-for="item in chaiyiyuanyins" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="盘点人" prop="pandian" :rules="[{ required: true, message: '请输入盘点人' }]">
                    <el-input v-model="form.pandian"></el-input>
                </el-form-item>
                <el-form-item label="盘点时间" prop="pandianshijian">
                    <el-date-picker v-model="form.pandianshijian" disabled placeholder="自动生成">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="状态" prop="zhuangtai" :rules="[{ required: true, message: '请选择状态' }]">
                    <el-select v-model="form.zhuangtai" placeholder="选择状态">
                        <el-option value="1" label="1"></el-option>
                        <el-option value="2" label="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="$router.back()">取消</el-button>
                    <el-button type="primary" @click="submitFrom">提交</el-button>
                </el-form-item>
            </el-form>
        </el-card>

    </div>
</template>

<script setup>
import { ref, defineEmits, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/api/request';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter();

const materialList = ref([]);

let emits = defineEmits(["closeDialog"])
let formRef = ref(null)
const route = useRoute();
const chaiyiyuanyins = ref([
    { value: "无差异", label: "无差异" },
    { value: "自然损耗", label: "自然损耗" }
])
const getMaterialList = async () => {
    try {
        const res = await request({
            method: "get",
            url: "/material/index",
            params:{
                size:1000,
                current:1
            }
        });
        if (res.data) {
             materialList.value = res.data.records;
        } else {
            ElMessage.error("获取物料列表失败");
        }
    } catch (err) {
        console.error("获取物料失败：", err);
        ElMessage.error("网络错误，无法加载物料");
    }
};
onMounted(() => {
    const countId = route.query.countId;
    if (countId) {
        form.value.didan = countId;
    }
    getMaterialList();
})
const form = ref({
    id: '',
    didan: '',
    wuliao: '',
    pici: '',
    typediaoru: '',
    diaoboleix: '',
    chayi: '',
    chaiyiyuanyin: '',
    pandian: '',
    pandianshijian: '',
    zhuangtai: ''
});
const calcDifference = () => {
    const typediaorud = Number(form.value.typediaoru) || 0;
    const diaoboleixd = Number(form.value.diaoboleix) || 0;

    let diff = diaoboleixd - typediaorud;
    form.value.chayi = diff.toFixed(2);
};

const submitFrom = () => {
    formRef.value.validate((isValid) => {
        if (isValid) {
            const submitData = {
                countId: form.value.didan,
                materialId: form.value.wuliao,
                batchNo: form.value.pici,
                systemQuantity: form.value.typediaoru,
                countedQuantity: form.value.diaoboleix,
                varianceQuantity: form.value.chayi,
                varianceReason: form.value.chaiyiyuanyin,
                countedBy: form.value.pandian,
                countTime: form.value.pandianshijian,
                status: form.value.zhuangtai
            };
            request({
                method: "post",
                url: "/inventory_sa/insect",
                data: submitData
            }).then(res => {
                if (res.data?.success) {
                    ElMessage.success("新增成功!");
                    router.push('/stock/take');
                } else {
                    const errMsg = res.data?.message || '未知错误'
                    console.error("新增失败:", errMsg);
                    ElMessage.error(`新增失败: ${errMsg}`);
                }
            }).catch(err => {
                console.error("请求异常:", err);
                ElMessage.error(`提交失败: ${err.message || '网络错误'}`);
            });
        }
    });
};
</script>
<style scoped>
.insert-container {
    padding: 20px;
}

.el-breadcrumb {
    margin-bottom: 20px;
}
</style>
